package com.amap.driveroute;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.driveroute.util.AMapUtil;
import com.amap.driveroute.util.ToastUtil;

public class MainActivity extends AppCompatActivity {

    private AMap aMap;//地图对象
    private MapView mapView;//地图View
    private Context mContext;//上下文
    private RouteSearch mRouteSearch;//路劲规划搜索的类
    private DriveRouteResult mDriveRouteResult;//路劲规划的结果
    private LatLonPoint mStartPoint = new LatLonPoint(39.942295, 116.335891);//起点，116.335891,39.942295
    private LatLonPoint mEndPoint = new LatLonPoint(39.995576, 116.481288);//终点，116.481288,39.995576
    private LatLonPoint mStartPoint_bus = new LatLonPoint(40.818311, 111.670801);//起点，111.670801,40.818311
    private LatLonPoint mEndPoint_bus = new LatLonPoint(44.433942, 125.184449);//终点，
    private String mCurrentCityName = "北京";
    private final int ROUTE_TYPE_BUS = 1;
    private final int ROUTE_TYPE_DRIVE = 2;
    private final int ROUTE_TYPE_WALK = 3;
    private final int ROUTE_TYPE_CROSSTOWN = 4;

    private RelativeLayout mBottomLayout;//详情的容器
    private TextView mRotueTimeDes;//时间距离的描述
    private TextView mRouteDetailDes;//打车约多少钱
    private ProgressDialog progDialog = null;// 搜索时进度条

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initParamsAndValues();

        initView(savedInstanceState);

        initMap();

        initRouteSearch();

        setFromAndToMarker();
    }

    private void initRouteSearch() {
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(mOnRouteSearchListener);//路径搜索结果监听接口设置
    }

    private void initView(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(R.id.route_map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        mBottomLayout = (RelativeLayout) findViewById(R.id.bottom_layout);
        mRotueTimeDes = (TextView) findViewById(R.id.firstline);
        mRouteDetailDes = (TextView) findViewById(R.id.secondline);
    }

    private void initParamsAndValues() {
        mContext = this.getApplicationContext();
    }

    /**
     * 设置起点到终点的Marker点
     */
    private void setFromAndToMarker() {
        aMap.addMarker(new MarkerOptions()
                .position(AMapUtil.convertToLatLng(mStartPoint))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
        aMap.addMarker(new MarkerOptions()
                .position(AMapUtil.convertToLatLng(mEndPoint))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }

        aMap.setOnMapClickListener(mOnMapClickListener);
        aMap.setOnMarkerClickListener(mOnMarkerClickListener);

    }

    /**
     * Map被点击执行的方法
     */
    AMap.OnMapClickListener mOnMapClickListener = new AMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

        }
    };

    /**
     * Marker点被点击的时候执行的方法
     */
    AMap.OnMarkerClickListener mOnMarkerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            return false;
        }
    };

    /**
     * 路径搜索结果的异步处理回调接口。
     */
    RouteSearch.OnRouteSearchListener mOnRouteSearchListener = new RouteSearch.OnRouteSearchListener() {

        /**
         * 公交换乘路劲规划结果的回调
         * @param busRouteResult 定义了公交路径规划的结果集。
         * @param i 返回结果成功或者失败的响应码.
         *          1000为成功(V3.2.1之后搜索成功响应码为1000，之前版本为0)，其他为失败（详细信息参见网站开发指南-错误码对照表）。
         */
        @Override
        public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

        }

        /**
         * 驾车路径规划结果的回调方法。
         * @param driveRouteResult
         * @param errorCode
         */
        @Override
        public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
            dissmissProgressDialog();
            aMap.clear();// 清理地图上的所有覆盖物
            if (errorCode == 1000) {//成功
                if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                    if (driveRouteResult.getPaths().size() > 0) {
                        mDriveRouteResult = driveRouteResult;
                        //1、获取规划结果的数据
                        final DrivePath drivePath = mDriveRouteResult.getPaths().get(0);//汽车的路劲

                        //2、驾车线路图层的设置类，用来设置驾车路线
                        DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                                mContext,
                                aMap,
                                drivePath,
                                mDriveRouteResult.getStartPos(),//起点
                                mDriveRouteResult.getTargetPos(),//终点
                                null);//转弯点
                        drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                        drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                        drivingRouteOverlay.removeFromMap();//移除绘制的线路
                        drivingRouteOverlay.addToMap();//添加驾车/步行/骑行路线到地图上显示。
                        drivingRouteOverlay.zoomToSpan();//将地图zoom到可以全览全路段的级别

                        //3、获取驾车方案的数据，比如距离，时间，
                        int dis = (int) drivePath.getDistance();//返回此规划方案的距离，单位米。
                        int dur = (int) drivePath.getDuration();//返回方案的预计消耗时间，单位秒。
                        int taxiCost = (int) mDriveRouteResult.getTaxiCost();//花费

                        //4、将获取到的数据设置到对应的控件上。
                        mBottomLayout.setVisibility(View.VISIBLE);
                        String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
                        mRotueTimeDes.setText(des);
                        mRouteDetailDes.setVisibility(View.VISIBLE);
                        mRouteDetailDes.setText("打车约" + taxiCost + "元");

                        mBottomLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(mContext, DriveRouteDetailActivity.class);
                                intent.putExtra("drive_path", drivePath);
                                intent.putExtra("drive_result", mDriveRouteResult);
                                startActivity(intent);
                            }
                        });
                    } else if (driveRouteResult != null && driveRouteResult.getPaths() == null) {
                        ToastUtil.show(mContext, R.string.no_result);
                    }

                } else {
                    ToastUtil.show(mContext, R.string.no_result);
                }
            } else {
                ToastUtil.showerror(mContext.getApplicationContext(), errorCode);
            }

        }

        /**
         * 骑行路径规划结果的回调方法。
         * @param walkRouteResult
         * @param i
         */
        @Override
        public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

        }

        /**
         * 步行路径规划结果的回调方法。
         * @param rideRouteResult
         * @param i
         */
        @Override
        public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

        }
    };

    /**
     * 路劲导航
     *
     * @param view
     */
    public void onDriveClick(View view) {
        searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DRIVING_SINGLE_DEFAULT);
        mapView.setVisibility(View.VISIBLE);
    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        //1、对起始点和终止点进行判断
        if (mStartPoint == null) {
            ToastUtil.show(mContext, "起点未设置");
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.show(mContext, "终点未设置");
        }
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);//构造路劲规划的起点和终点坐标
        if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划

            //驾车路劲查询规划
            // 第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                            fromAndTo,// 第一个参数表示路径规划的起点和终点，
                            mode,//计算路劲的模式。可选，默认为速度优先RouteSearch.DrivingDefault。
                            null,//途径点，可选。最多支持16个途径点。
                            null,//避让区域，可选。
                            "");//避让道路名称，可选，目前支持一条避让道路。

            //根据指定的参数来计算驾车路劲的异步处理
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        }
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索...");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}
